package com.example.performance.jol.official;

import org.openjdk.jol.info.ClassLayout;
import org.openjdk.jol.vm.VM;

/**
 * @author Aleksey Shipilev
 */
@SuppressWarnings({"java:S101", "java:S106", "java:S2094", "SynchronizationOnLocalVariableOrMethodParameter"})
public class JOLSample_13_ThinLocking {

    /*
     * This is another dive into the mark word.
     *
     * This one is the example of thin (displaced) lock. The data
     * in mark word when lock is acquired is the reference to the
     * displaced object header, allocated on stack. Once we leave
     * the lock, the displaced header is discarded, and mark word
     * is reverted to the default value.
     *
     * This example relies on biased locking not biasing the object
     * at the first lock acquisition. Since JDKs up to 8 have biased
     * locking startup delay, this example works out of the box there.
     * On modern JDKs, starting with 9, this example should be run
     * with -XX:-UseBiasedLocking.
     */

    public static void main(String[] args) {
        System.out.println(VM.current().details());

        final A a = new A();

        ClassLayout layout = ClassLayout.parseInstance(a);

        System.out.println("**** Fresh object");
        System.out.println(layout.toPrintable());

        synchronized (a) {
            System.out.println("**** With the lock");
            System.out.println(layout.toPrintable());
        }

        System.out.println("**** After the lock");
        System.out.println(layout.toPrintable());
    }

    public static class A {
        // no fields
    }

}
